package com.beiye.drivertransport.thematic.learning;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.PayMentBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//专项培训旧支付界面暂时不用
 public class PaymentActivity extends TwoBaseAty {

    ImageView img_payback;

    TextView tv_special;

    TextView tv_price;

    TextView tv_pay3;//购买

    TextView tv_balance;//余额

    TextView tv_pay2;

    TextView tv_money2;//差值

    ImageView img_pay;
    private float price;
    private IWXAPI api;
    private PopupWindow mUserPopWindow;
    //    @Bind(R.id.rg)
//    LiumRadioGroup rg;
//    @Bind(R.id.radioButton_pay)
//    RadioButton radioButton_pay;
//    @Bind(R.id.radioButton_pay1)
//    RadioButton radioButton_pay1;
  //  private IWXAPI api;

    @Override
     public int getLayoutId() {
         return R.layout.activity_payment;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_payback) {
            finish();
        } else if (id == R.id.tv_pay3) {
            if (Utils.isFastClicker()) {
                return;
            }
            SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
            String idcNo = sp.getString("idcNo", "");
            if (idcNo.equals("")) {
                showpopwindow();//身份证验证
                return;
            }
            payment();//支付方法
        }
    }
    //支付方法
    public void payment()
    {
        SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
        if(tv_pay3.getText().toString().trim().equals("余额购买")) {
            String orgId = sp.getString("orgId", "");
            float diffentprice = sp.getFloat("diffentprice", 0);
            int stId = sp.getInt("stId", 0);
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            String userId = data.getUserId();
            String phoneSign = getPhoneSign();//设备的唯一标识
            showLoadingDialog("");//余额支付
            new Login().getPayMentApp(userId, orgId, 3, stId, "APP", diffentprice, phoneSign, Constants.APP_ID, null,this, 2);
            tv_pay3.setEnabled(false);
        }else if(tv_pay3.getText().toString().trim().equals("充值余额并购买"))
        {
            boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if(!isPaySupported)
            {
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(PaymentActivity.this);
                builder1.setMessage("该微信版本不支持微信支付");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();;
                    }
                });
                builder1.create().show();
                return;
            }
            String orgId = sp.getString("orgId", "");
            float diffentprice = sp.getFloat("diffentprice", 0);
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            String userId = data.getUserId();
            String phoneSign = getPhoneSign();//设备的唯一标识
            Toast.makeText(PaymentActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
            tv_pay3.setEnabled(false);//微信支付
            new Login().getbalanceMentApp(userId,orgId, 2,"APP",diffentprice, phoneSign, Constants.APP_ID,this, 3);
        }

    }



    private void showpopwindow() {

        View contentView = LayoutInflater.from(PaymentActivity.this).inflate(R.layout.checkuser_popwindowlayout, null);
        mUserPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        EditText   ed_id = (EditText) contentView.findViewById(R.id.ed_id);
        mUserPopWindow.showAtLocation(ed_id, Gravity.CENTER, 0, 0);
// 编辑框设置触摸监听
        ed_id.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    ed_id.setCursorVisible(true);// 再次点击显示光标
                }
                return false;
            }
        });
        TextView tv_idsave = (TextView) contentView.findViewById(R.id.tv_idsave);
        tv_idsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // mUserPopWindow.dismiss();
                String id = ed_id.getText().toString().trim();
                if(id.equals(""))
                {
                    showToast("身份证不为空");
                    return;
                }
                if (!IsIDcard(id)) {
                    showToast("身份证无效");
                    return;
                }
                LoginUserBean userInfo1 = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo1.getData();
                String userId = data.getUserId();
                ImputUserID(userId,id);

            }
        });

    }

    private void ImputUserID(String userId, String id) {
        showLoadingDialog("");
        new Login().getImputUserID(userId, id,this,5);

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if(event.getType()==MessageEvent.TYPE_9)
        {
            SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
         //   float diffentprice = sp.getFloat("diffentprice", 0);
            int stId = sp.getInt("stId", 0);
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            String userId = data.getUserId();
            String phoneSign = getPhoneSign();//设备的唯一标识
            showLoadingDialog("");//余额支付
            new Login().getPayMentApp(userId, orgId, 3, stId, "APP", price, phoneSign, Constants.APP_ID, null,this, 2);
        }else if(event.getType()==MessageEvent.TYPE_8)
        {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(PaymentActivity.this);
            builder1.setMessage("你充值失败");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                }
            });

            builder1.create().show();
        }
    }





    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }

    @Override
     public void initData() {
        img_payback = (ImageView) findViewById(R.id.img_payback);
        tv_special = (TextView) findViewById(R.id.tv_pay4);
        tv_price = (TextView) findViewById(R.id.tv_money);
        tv_pay3 = (TextView)findViewById(R.id.tv_pay3);
        tv_balance = (TextView)findViewById(R.id.tv_money1);
        tv_pay2 = (TextView) findViewById(R.id.tv_pay2);
        tv_money2 = (TextView)findViewById(R.id.tv_money2);
        img_pay = (ImageView) findViewById(R.id.img_pay);

        //注册EventBus
        EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
         Bundle bundle = getIntent().getExtras();
         int stId = bundle.getInt("stId");
         String orgId = bundle.getString("orgId");
         String stName = bundle.getString("stName");
         int paytag = bundle.getInt("paytag");
         price = bundle.getFloat("price");

        String twoDecimal = getTwoDecimal(price);
         if(price <1)
         {
             tv_price.setText("0"+twoDecimal+"元");
         }else if(price >=1){
             tv_price.setText(twoDecimal+"元");
         }
         SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
         SharedPreferences.Editor edit = sp.edit();
         edit.putString("orgId",orgId);
         edit.putInt("stId",stId);
         edit.putInt("paytag",paytag);
         edit.putString("twoDecimal",twoDecimal);
         edit.commit();
//        SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
//        SharedPreferences.Editor edit1 = sp1.edit();
//        edit1.putString("orgId",orgId);
//        edit1.putString("orgName",orgName);
//        edit1.putString("iconUrl",iconUrl);
//        edit1.putInt("stId",stId);

        if(stName.equals(""))
         {
             tv_special.setText("");
         }else{
             tv_special.setText(stName);
         }



//         rg.setOnCheckedChangeListener(new LiumRadioGroup.OnCheckedChangeListener() {
//             @Override
//             public void onCheckedChanged(LiumRadioGroup group, int checkedId) {
//                 switch (checkedId) {
//                     case R.id.radioButton_pay:
//                         SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
//                         SharedPreferences.Editor edit = sp.edit();
//                         edit.putInt("wechat",1);
//                         edit.commit();
//                         break;
//                     case R.id.radioButton_pay1:
//                         SharedPreferences sp1 = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
//                         SharedPreferences.Editor edit1 = sp1.edit();
//                         edit1.putInt("wechat",2);
//                         edit1.commit();
//                         break;
//                 }
//             }
//         });


     }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
         if(what==1)
         {
//             SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
//             int paytag = sp.getInt("paytag", 0);
//             PayMentBean payMentBean = JSON.parseObject(result, PayMentBean.class);
//             String msg = payMentBean.getMsg();//支付订单系列号
//             SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
//             SharedPreferences.Editor edit1 = sp1.edit();
//             edit1.putString("msg",msg);
//             edit1.putInt("paytag",paytag);
//             edit1.commit();
//                 PayMentBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
//              if(paydata!= null)
//              {
//                  api.registerApp(Constants.APP_ID);
//                 PayReq req = new PayReq();
//                  req.appId = Constants.APP_ID;
//                  req.packageValue = "Sign=WXPay";
//                  req.partnerId = paydata.getPartnerid();
//                  req.prepayId = paydata.getPrepayid();
//                  req.nonceStr = paydata.getNoncestr();
//                  req.timeStamp = paydata.getTimestamp();
//                  req.sign = paydata.getSign();
//                  api.sendReq(req);
//                  finish();
//              }
//
//             tv_pay3.setEnabled(true);
             MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
             MineUseBean.DataBean data = mineUseBean.getData();
             float balance = data.getBalance();
             String twoDecimal = getTwoDecimal(balance);
             tv_balance.setText(twoDecimal+"元");
             if(balance<price)
             {
                 float difference=price-balance;
                 SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
                 SharedPreferences.Editor edit = sp.edit();
                 String twoDecimal1 = getTwoDecimal(difference);
                 float differencefloat = Float.parseFloat(twoDecimal1);
                 tv_money2.setText("需付金额："+differencefloat+"元");
                 edit.putFloat("diffentprice",differencefloat);
                 edit.commit();
                 img_pay.setImageResource(R.mipmap.wechatpay);
                 tv_pay2.setText("微信支付");
                 tv_pay3.setText("充值余额并购买");
             }else{
                 SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
                 SharedPreferences.Editor edit = sp.edit();
                 edit.putFloat("diffentprice",price);
                 edit.commit();
                 tv_money2.setText("本次购买金额充足");
                 img_pay.setImageResource(R.mipmap.balancepayment);
                 tv_pay2.setText("余额支付");
                 tv_pay3.setText("余额购买");
             }

         }else if(what==2)
         {
             dismissLoadingDialog();
             SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
             int paytag = sp.getInt("paytag", 0);
             if(paytag==1)//退回首页界面
             {
                 EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_1));
                 finish();

             }else if(paytag==2)//退回专项培训全部专题界面
             {
                 EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_2));
                 finish();


             }else if(paytag==3)//退回专项培训里考试界面
             {
                 EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_3));
                 finish();
             }
             tv_pay3.setEnabled(true);
         }else if(what==3)
         {
             PayMentBean payMentBean = JSON.parseObject(result, PayMentBean.class);
             String msg = payMentBean.getMsg();//支付订单系列号
             SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
             SharedPreferences.Editor edit1 = sp1.edit();
             edit1.putString("msg",msg);
             edit1.putInt("paytag",6);
             edit1.commit();
             PayMentBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
              if(paydata!= null)
              {
                  api.registerApp(Constants.APP_ID);
                 PayReq req = new PayReq();
                  req.appId = Constants.APP_ID;
                  req.packageValue = "Sign=WXPay";
                  req.partnerId = paydata.getPartnerid();
                  req.prepayId = paydata.getPrepayid();
                  req.nonceStr = paydata.getNoncestr();
                  req.timeStamp = paydata.getTimestamp();
                  req.sign = paydata.getSign();
                  api.sendReq(req);

              }
             tv_pay3.setEnabled(true);
         }else if(what==4)
         {
             MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
             MineUseBean.DataBean data = mineUseBean.getData();
             String idcNo = data.getIdcNo();
             if(idcNo==null)
             {
                 SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
                 SharedPreferences.Editor edit = sp.edit();
                 edit.putString("idcNo", "");
                 edit.commit();
             }else {
                 SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
                 SharedPreferences.Editor edit = sp.edit();
                 edit.putString("idcNo", idcNo);
                 edit.commit();
             }
         }else if(what==5)
         {
             dismissLoadingDialog();
             mUserPopWindow.dismiss();
             LoginUserBean userInfo = UserManger.getUserInfo();
             LoginUserBean.DataBean data = userInfo.getData();
             String userId = data.getUserId();
             new Login().getUser(userId,this,4);   //再次验证是否有身份证信息判断按钮是否为灰
             payment();

         }
        super.onSuccess(result, call, response, what);
    }


    @Override
    public void onError(String result, Call call, Response response, int what) {
//         if(what==1)
//         {
//             CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//             //     int code = checkBean.getCode();
//             String msg = checkBean.getMsg();
//             TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
//             builder1.setMessage(msg);
//             builder1.setTitle("提示:");
//             builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
//                 public void onClick(DialogInterface dialog, int which) {
//                     dialog.dismiss();;
//                     //设置你的操作事项
//                 }
//             });
//             builder1.create().show();
//
//
//         }else
             if(what==2)
         {
             dismissLoadingDialog();
             tv_pay3.setEnabled(true);
             CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
             //     int code = checkBean.getCode();
             String msg = checkBean.getMsg();
             TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
             builder1.setMessage(msg);
             builder1.setTitle("提示:");
             builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {
                     dialog.dismiss();
                     ;
                     //设置你的操作事项
                 }
             });
             builder1.create().show();
//             if(msg.contains("余额不足"))
//             {
//                 TiShiDialog.Builder builder1 = new TiShiDialog.Builder(PaymentActivity.this);
//                 builder1.setMessage(msg);
//                 builder1.setTitle("提示:");
//                 builder1.setPositiveButton("进入充值界面", new DialogInterface.OnClickListener() {
//                     public void onClick(DialogInterface dialog, int which) {
//                         dialog.dismiss();
//                         //设置你的操作事项
//                         SharedPreferences sp = getSharedPreferences("PaymentActivity", Context.MODE_PRIVATE);
//                         String orgId = sp.getString("orgId", "");
//                         Bundle bundle = new Bundle();
//                         bundle.putString("orgId", orgId);
//                         startActivity(AccountbalanceActivity.class, bundle);
//                     }
//                 });
//                 builder1.setNegativeButton("取消",
//                         new android.content.DialogInterface.OnClickListener() {
//                             public void onClick(DialogInterface dialog, int which) {
//                                 dialog.dismiss();
//                             }
//                         });
//
//                 builder1.create().show();
//
//
//
//             }
//             else {
//                 TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
//                 builder1.setMessage(msg);
//                 builder1.setTitle("提示:");
//                 builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
//                     public void onClick(DialogInterface dialog, int which) {
//                         dialog.dismiss();
//                         ;
//                         //设置你的操作事项
//                     }
//                 });
//                 builder1.create().show();
//             }
         }else if(what==3)
             {
                 tv_pay3.setEnabled(true);
                 CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
                 String msg = checkBean.getMsg();
                 TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                 builder1.setMessage(msg);
                 builder1.setTitle("提示:");
                 builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                         dialog.dismiss();;
                         //设置你的操作事项
                     }
                 });
                 builder1.create().show();
             }if(what==5)
        {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            String msg = checkBean.getMsg();
            dismissLoadingDialog();
            showToast(msg);


        }
        super.onError(result, call, response, what);
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        LoginUserBean.DataBean data = userInfo.getData();
//        String userId = data.getUserId();
//        new Login().getUser(userId,this,4);   //验证是否有身份证
//    }

    /**
     * 将数据保留两位小数
     */
    private String getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#0.00");
        String yearString = dFormat.format(num);
        return yearString;
    }

     @Override
     public void requestData() {

         LoginUserBean userInfo = UserManger.getUserInfo();
         LoginUserBean.DataBean data = userInfo.getData();
         String userId = data.getUserId();
         showLoadingDialog("");
         new Login().getUser(userId,this,1);
         new Login().getUser(userId,this,4);//验证身份证


     }
    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign(){
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
           // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if(!TextUtils.isEmpty(imei)){
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if(!TextUtils.isEmpty(sn)){
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if(!TextUtils.isEmpty(uuid)){
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }
    /**
     * 得到全局唯一UUID
     */
    private String uuid;
    public String getUUID(){
        SharedPreferences mShare = getSharedPreferences("uuid",MODE_PRIVATE);
        if(mShare != null){
            uuid = mShare.getString("uuid", "");
        }
        if(TextUtils.isEmpty(uuid)){
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid",uuid).commit();
        }
        return uuid;
    }
    /**
     * 验证输入身份证号
     *
     * @param
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public  boolean IsIDcard(String str) {
        String regex = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
        return match(regex, str);
    }
    /**
     * @param regex
     * 正则表达式字符串
     * @param str
     * 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private  boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
 }
